const express = require('express')
const router = express.Router()
const users = require('../models/user')
const jwt = require('jsonwebtoken')

// 获取用户信息
router.get('/userInfo', (req, res) => {
  let token = req.get("Authorization")
  jwt.verify(token, 'abc', (err, decode) => {
    if (err) return res.send({code: 0, message: "token已失效"})
    users.findOne({
      username: decode.username,
      password: decode.password
    }, (err, data) => {
      if (err) {
        return res.status(403).send({
          message: 'token已失效',
          status: 403
        })
      } else {
        res.send({
          message: '获取用户信息成功',
          status: 200,
          data: {
            gender: data.gender,
            introduce: data.introduce,
            modyfyDate: data.modyfyDate,
            regDate: data.regDate,
            username: data.username,
            _id: data._id,
          }
        })
      }
    })
  })
})

// 修改用户信息
router.post('/updateUserInfo', (req, res) => {
  let token = req.get("Authorization")
  jwt.verify(token, 'abc', (err, decode) => {
    if (err) return res.send({code: 0, message: "token已失效"})
    users.findOneAndUpdate({
      username: decode.username,
      password: decode.password
    }, req.body, { new: true }, (err, data) => {
      if (err) {
        return res.status(403).send({
          message: '用户名或密码错误',
          status: 403
        })
      } else {
        res.send({
          message: '修改用户信息成功',
          status: 200
        })
      }
    })
  })
})

// 修改密码
router.post('/updatePassword', (req, res) => {
  let token = req.get("Authorization")
  jwt.verify(token, 'abc', (err, decode) => {
    if (err) return res.send({code: 0, message: "token已失效"})
    users.findOneAndUpdate({
      username: decode.username,
      password: decode.password
    }, req.body, { new: true }, (err, data) => {
      if (err) {
        return res.status(403).send({
          message: '修改密码错误',
          status: 403
        })
      } else {
        res.send({
          message: '修改密码成功',
          status: 200
        })
      }
    })
  })
})

module.exports = router
